package com.futong.cloud.function;

import com.futong.cloud.action.ActionConsumer;
import com.futong.cloud.action.ActionException;
import com.futong.cloud.action.ActionModel;
import com.futong.cloud.utils.ScriptUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import javax.script.ScriptException;
import java.util.List;
@Slf4j
public class Validate {
    public static ActionConsumer request=context -> {
        List<ActionModel.ActionFiledModel> fileds = context.getActionModel().getFileds();
        if(CollectionUtils.isNotEmpty(fileds)){
            fileds.stream().filter(field->"request".equalsIgnoreCase(field.getScope())&&StringUtils.isNotEmpty(field.getValid())).forEach(filed->{
                String script="_"+filed.getId()+"("+context.getRequest()+")";
                try {
                    String rs = ScriptUtils.execStr(script);
                    if(StringUtils.isNotEmpty(rs))throw new ActionException(rs,302);
                } catch (ScriptException e) {
                    log.error("script errer:{}",script);
                    throw new ActionException("校验语法错误",502);
                }
            });
        }
    };
}
